package kaist.sep521.lego.circlebicycle;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ParserHandler extends DefaultHandler {
	private String position = "";
	private User pUser;
	private ArrayList<User> pUserList;

	public ArrayList<User> getParsedData() {
		return this.pUserList;
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);

		String str = new String(ch, start, length).trim();
		if (position.equals("id")) {
			pUser.setID(str);
			position = "";
		}

		if (position.equals("nickname")) {
			pUser.setNickname(str);
			position = "";
		}

		if (position.equals("horizontal")) {
			pUser.setLatitude(Float.parseFloat(str));
			position = "";
		}

		if (position.equals("vertical")) {
			pUser.setLongitude(Float.parseFloat(str));
			position = "";
		}

		if (position.equals("status")) {
			pUser.setStatus(Integer.parseInt(str));
			position = "";
		}

		if (position.equals("group")) {
			pUser.setGroup(str);
			position = "";
		}
		
		if (position.equals("voice")) {
			pUser.setVoice(Integer.parseInt(str));
			position = "";
		}
		
		if (position.equals("sharelocation")) {
			pUser.setShareLocation(Boolean.parseBoolean(str));
			position = "";
		}
	}

	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		this.pUserList = new ArrayList<User>();
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		if (qName.equals("UserEntry")) {
			pUser = new User();
		} else if (qName.equals("id")) {
			position = "id";
		} else if (qName.equals("nickname")) {
			position = "nickname";
		} else if (qName.equals("horizontal")) {
			position = "horizontal";
		} else if (qName.equals("vertical")) {
			position = "vertical";
		} else if (qName.equals("status")) {
			position = "status";
		} else if (qName.equals("group")) {
			position = "group";
		}else if (qName.equals("voice")) {
			position = "voice";
		}else if (qName.equals("sharelocation")) {
			position = "sharelocation";
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		super.endElement(uri, localName, qName);
		if (qName.equals("UserEntry")) {
			pUserList.add(pUser);
		}
	}
}
